﻿import os
import cv2
import numpy as np
from collections import defaultdict

# 图片文件夹路径
input_folder = './SourceVideo'
# 输出文件夹路径
output_folder = 'resized_images/1_out'
# 新的图片宽度和高度
new_width = 320
new_height = 80
# 渐变帧数量（两段视频之间插入几张）
transition_frames = 40

# 如果输出文件夹不存在，则创建
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 提取前缀和数字
def split_prefix_number(filename):
    name, _ = os.path.splitext(filename)
    prefix = ''.join([c for c in name if not c.isdigit()])  # 非数字部分
    num_str = ''.join([c for c in name if c.isdigit()])     # 数字部分
    return prefix, int(num_str) if num_str.isdigit() else 0

# 分组
groups = defaultdict(list)
for filename in os.listdir(input_folder):
    if filename.lower().endswith(('.bmp', '.png', '.jpg', '.jpeg')):
        prefix, num = split_prefix_number(filename)
        groups[prefix].append((filename, num))

image_index = 0
sorted_prefixes = sorted(groups.keys())

for p_idx, prefix in enumerate(sorted_prefixes):
    sorted_group = sorted(groups[prefix], key=lambda x: x[1])

    for filename, _ in sorted_group:
        img_path = os.path.join(input_folder, filename)
        image = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)

        if image is None:
            print(f"Warning: Cannot read file {filename}")
            continue

        # 修改图片尺寸
        resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)

        # 保存原图
        image_index += 1
        new_filename = f'seq{image_index}.bmp'
        output_img_path = os.path.join(output_folder, new_filename)
        cv2.imwrite(output_img_path, resized_image)
        print(f'Saved image: {output_img_path}')

    # 如果不是最后一个视频组，则在组与组之间插入渐变帧
    if p_idx < len(sorted_prefixes) - 1:
        next_prefix = sorted_prefixes[p_idx + 1]
        last_filename, _ = sorted_group[-1]  # 当前视频最后一帧
        next_first_filename, _ = sorted(groups[next_prefix], key=lambda x: x[1])[0]  # 下一个视频第一帧

        last_img = cv2.imread(os.path.join(input_folder, last_filename), cv2.IMREAD_GRAYSCALE)
        next_img = cv2.imread(os.path.join(input_folder, next_first_filename), cv2.IMREAD_GRAYSCALE)

        if last_img is None or next_img is None:
            print(f"Warning: Cannot read transition images between {prefix} and {next_prefix}")
            continue

        last_resized = cv2.resize(last_img, (new_width, new_height), interpolation=cv2.INTER_AREA)
        next_resized = cv2.resize(next_img, (new_width, new_height), interpolation=cv2.INTER_AREA)

        # 生成渐变帧
        for t in range(1, transition_frames + 1):
            alpha = t / (transition_frames + 1)
            blended = cv2.addWeighted(last_resized, 1 - alpha, next_resized, alpha, 0)
            image_index += 1
            blend_filename = f'seq{image_index}.bmp'
            blend_output_path = os.path.join(output_folder, blend_filename)
            cv2.imwrite(blend_output_path, blended)
            print(f'Added transition frame between {prefix} and {next_prefix}: {blend_output_path}')
